﻿package org.cshoo.common.authentication;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.cshoo.sys.data.entity.Role;
import org.cshoo.sys.data.entity.User;
import org.cshoo.sys.data.idao.IUserDAO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author 杨翼
 * 此类用于spring security登陆验证
 * 2013年4月8日
 */
public class CshooUserDetailsService implements UserDetailsService {
	
	private IUserDAO userDAO;

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	@Override
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		User userExample = new User();
		userExample.setUserName(userName);
		
		List userList = userDAO.findObjectListByExample(userExample);
		if(userList.size() == 0){
			throw new UsernameNotFoundException("没有用户名为“"+ userName + "”的用户");
		}
		User user = (User)userList.get(0);
		Boolean enabled = user.getEnabled() == null ? true : user.getEnabled().equals("启用");
		
		Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();
		Set<Role> roleSet = user.getRoleSet();
		Iterator it = roleSet.iterator();
		while(it.hasNext()){
			Role role = (Role)it.next();
			String roleName = role.getCode();
			GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
			dbAuthsSet.add(authority);
		}
        List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthsSet);
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(userName, user.getPassword(), enabled, true, true, true, dbAuths);
        return userDetails;
	}
}
